﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Win32;
using System.Net;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.Xml;

namespace sentence
{
    class WallPaperDownloader
    {
        XmlDocument xmldoc= new XmlDocument();
        String Date;
        public static String SavePath = System.IO.Path.GetTempPath();
        public WallPaperDownloader()
        {
            Thread Thread_CheckDesktop = new Thread(new ThreadStart(CheckDesktopThread));
            Thread_CheckDesktop.IsBackground = true;
            Thread_CheckDesktop.Start();
        }
        public void CheckDesktopThread()
        {
            try
            {
                while (true)
            {
                if (File.Exists(Application.StartupPath + @"\config.xml"))
                {
                    break;
                }
                Thread.Sleep(5000);
            }
            //加入判断过程
            Date = DateTime.Now.ToString("yyyyMMdd");
            String DownloadURL;
            do
            {
                if (int.Parse(Date) == int.Parse(SentenceUtility.WallPaperDate))
                {
                    break;
                }
                DownloadURL = SentenceUtility.DownloadURL;
                switch (SentenceUtility.MainScreenRatio)
                {
                    case SentenceUtility.ScreenRatio.SixteenByTen://1920x1200
                        DownloadURL += "?date=" + Date + "&ScreenRatio=0";
                        break;
                    case SentenceUtility.ScreenRatio.SixteenByNine://1920x1080
                        DownloadURL += "?date=" + Date + "&ScreenRatio=1";
                        break;
                    case SentenceUtility.ScreenRatio.FourByThree://1600x1200
                        DownloadURL += "?date=" + Date + "&ScreenRatio=2";
                        break;
                    case SentenceUtility.ScreenRatio.NO_MATCH:
                        DownloadURL += "?date=" + Date + "&ScreenRatio=0";
                        break;
                }
                SavePath += Date + ".jpg";
                if (!DownloadWallpaper(DownloadURL))
                {
                    //TBD
                    
                }
                else
                {
                    if (System.Environment.OSVersion.Version.Major < 6)
                    {
                        ApplyWallpaperXP(SavePath);
                    }
                    else
                    {
                        ApplyWallpaperWin7(SavePath);
                    }
                }
                Thread.Sleep(60 * 1000);
            } while (true);

            return;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("软件发生了一个错误，\r\n请发送错误报告以便我们修复这个BUG", "SORRY%>_<%");
                BUGReport reporter = new BUGReport(ex.ToString());
                reporter.ReportSend();
            }
            
            
        }

        public bool DownloadWallpaper(string url)
        {
            try
            {
                WebClient downclient = new WebClient();
                downclient.DownloadFile(url, SavePath);
            }
            catch(System.Exception ex)
            {
                return false;
            }


            return true;
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

        public void ApplyWallpaperXP(string path)
        {
            try
            {
                RegistryKey myRegKey = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
                myRegKey.SetValue("TileWallpaper", "0");
                myRegKey.SetValue("WallpaperStyle", "2");
                myRegKey.Close();
                Bitmap bmpWallpaper = new Bitmap(path);

                string savePath = "";
                if (System.Environment.OSVersion.Version.Major < 6)
                {
                    savePath = Path.Combine(SentenceUtility.ApplicationDirectory, "DonotDelete-TranscodedWallpaper.bmp");
                }
                else
                {
                    savePath = Path.Combine(SentenceUtility.WorkingDirectory, "DonotDelete-TranscodedWallpaper.bmp");
                }
                bmpWallpaper.Save(savePath, ImageFormat.Bmp);

                SystemParametersInfo(20, 1, savePath, 1);

                xmldoc.Load(Application.StartupPath + @"\config.xml");
                XmlNode node = xmldoc.GetElementsByTagName("Sentence").Item(0);
                XmlElement e = (XmlElement)node;
                e.SetAttribute("WallPaperDate", Date);
                SentenceUtility.WallPaperDate = Date;
                xmldoc.Save("config.xml");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("软件发生了一个错误，\r\n请发送错误报告以便我们修复这个BUG", "SORRY%>_<%");
                BUGReport reporter = new BUGReport(ex.ToString());
                reporter.ReportSend();
            }
           
        }

        public void ApplyWallpaperWin7(string path)
        {
            try
            {
                //以拉伸显示壁纸
                RegistryKey myRegKey = Registry.CurrentUser.OpenSubKey("Control Panel\\desktop", true);
                myRegKey.SetValue("TileWallpaper", "0");
                myRegKey.SetValue("WallpaperStyle", "2");
                myRegKey.Close();

                Shell32.Shell shell = new Shell32.ShellClass();
                Shell32.Folder folder = shell.NameSpace(Path.GetDirectoryName(path)) as Shell32.Folder;
                Shell32.FolderItem folderItem = folder.ParseName(System.IO.Path.GetFileName(path));
                Shell32.FolderItemVerbs vs = folderItem.Verbs();

                bool wallpaperSet = false;
                for (int i = 0; i < vs.Count; i++)
                {
                    Shell32.FolderItemVerb ib = vs.Item(i);

                    if (ib.Name.Contains("&b") || ib.Name.Contains("&B"))
                    {
                        if (ib.Name.ToLower().Contains("background") || ib.Name.ToLower().Contains("背景"))
                        {
                            wallpaperSet = true;
                            ib.DoIt();
                        }
                    }
                }

                if (wallpaperSet == false)
                {
                    ApplyWallpaperXP(path);
                }
                else
                {
                    xmldoc.Load(Application.StartupPath + @"\config.xml");
                    XmlNode node = xmldoc.GetElementsByTagName("Sentence").Item(0);
                    XmlElement e = (XmlElement)node;
                    e.SetAttribute("WallPaperDate", Date);
                    SentenceUtility.WallPaperDate = Date;
                    xmldoc.Save("config.xml");
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("软件发生了一个错误，\r\n请发送错误报告以便我们修复这个BUG", "SORRY%>_<%");
                BUGReport reporter = new BUGReport(ex.ToString());
                reporter.ReportSend();
            }
            
        }
    }
}
